// 获取基础URL方式
var baseUrl = window.location.protocol + '//' + window.location.host;

// 需要加载的资源列表
var resources = [
    { type: 'script', path: '/public/js/main.js' },
    { type: 'script', path: '/public/lib/wsx/land.js' },
    { type: 'script', path: '/public/js/app.js' },
    { type: 'stylesheet', path: '/public/css/reset.min.css' },
    { type: 'stylesheet', path: '/public/css/common.min.css' },
    { type: 'stylesheet', path: '/public/css/font.css' },
    { type: 'stylesheet', path: '/public/css/theme.css' }
];

// 批量生成资源标签
for (var i = 0; i < resources.length; i++) {
    var resource = resources[i];
    var tag = '';
    
    if (resource.type === 'script') {
        tag = '<script type="text/javascript" src="' + baseUrl + resource.path + '"></script>';
    } else {
        tag = '<link rel="stylesheet" href="' + baseUrl + resource.path + '" />';
    }
    
    document.writeln(tag);
};

// 生成公共部分
function create(container = "body", select = 0, callback = null){
    ajax("GET", `${baseUrl}/api/json/data`).then(data => {
        if(data.success){
            let newData = [];
            for(let i = 0; i < data.data.menu.length; i++) {
                if(Number(data.data.menu[i].type === 1)) {
                    newData = setMenu(data.data.menu[i].data);
                    break;
                }
            };
            createHeaader(container, select, newData, callback);
            createFooter(container);
        } else {
            alert(data.message, null, "warning");
        }
    }).catch(error => {
        alert(error.message, null, "error");
    })
};

function setMenu(data) {
    const Menu = [];
    data.forEach(item => {
        let parent = findNode(Menu, item.uid);
        if(parent !== null) {
            if(!parent.children) parent.children = [];
            parent.children.push(item);
        } else {
            Menu.push(item);
        }
    })
    return Menu;
};

function findNode(treeList, parentID){
    for (let i = 0; i < treeList.length; i++) {
        let node = treeList[i];
        if (node.id === parentID) return node;
        else {
            if (node.children && node.children.length > 0) {
                let oRet = findNode(node.children, parentID);
                if (oRet !== null) {
                    return oRet;
                }
            }
        }
    }
    return null;
};

function isPathSet(url) {
    const isPortPath = /^:\d+$/.test(url);
    let urlParh = null;
    if(isPortPath) {
        const port = url.replace(':', '');
        urlParh = `${window.location.protocol}//${window.location.hostname}:${port}`;
    } else {
        urlParh = `${baseUrl}${url}`;
    };
    return urlParh;
};

function createHeaader(container, select, data, callback){
    let header = createTag("header", [["class", "header"]]);
    let mainContent = createTag("div", [["class", "mainContent rowStartCenter"]]);
    let img = new Image();
    img.src = `${baseUrl}/public/imgs/icon/logo.png`;
    img.className = "logo";
    img.alt = "logo";
    let fullHeight = createTag("div", [["class", "flex-1 rowEndCenter fullHeight"]]);
    for(let i = 0; i < data.length; i ++) {
        let itemMenu = createTag("div", [["class", `${Number(select) === i ? "select " : ""}item-menu rowCenterCenter rela`]]);
        let itemLink = null;
        if(data[i].path === "about:black") {
            itemLink = createTag("div", [["class", "item-link"], ["style", "cursor: default;"]]);
        } else {
            itemLink = createTag("a", [["class", "item-link"], ["href", isPathSet(data[i].path)]]);
        };
        let oneMenu = createTag("div", [["class", "oneMenu"]]);
        let ch_zn_1 = createTag("div", [["class", "rowCenterCenter"]], data[i].zh);
        let en_1 = createTag("div", [["class", "rowCenterCenter"]], data[i].en);
        oneMenu.appendChild(ch_zn_1);
        oneMenu.appendChild(en_1);
        itemLink.appendChild(oneMenu);
        itemMenu.appendChild(itemLink);
        if(data[i].children && data[i].children.length > 0) {
            let itemBox = createTag("div", [["class", "item-box"]]);
            let itemBox2 = createTag("div", [["class", "item-box-2"]]);
            for(let j = 0; j < data[i].children.length; j++) {
                let itemItem = createTag("div", [["class", "item-item"]]);
                let itemLink2 = createTag("a", [["class", "item-link"],["href", isPathSet(data[i].children[j].path)]]);
                let oneMenu2 = createTag("div", [["class", "oneMenu2"]]);
                let ch_zn_2 = createTag("div", [["class", "rowCenterCenter"]],data[i].children[j].zh);
                let en_2 = createTag("div", [["class", "rowCenterCenter"]],data[i].children[j].en);
                oneMenu2.appendChild(ch_zn_2);
                oneMenu2.appendChild(en_2);
                itemLink2.appendChild(oneMenu2);
                itemItem.appendChild(itemLink2);
                itemBox2.appendChild(itemItem);
            }
            itemBox.appendChild(itemBox2);
            itemMenu.appendChild(itemBox);
        };
        fullHeight.appendChild(itemMenu);
    };
    let searchIcon = createSvg("M774.991188 759.692531l201.863039 201.863039a36.569391 36.569391 0 0 1-51.782258 51.70912L717.138411 805.257993a438.832694 438.832694 0 1 1 57.779638-45.565462zM475.561014 804.526605A365.693911 365.693911 0 1 0 475.561014 73.138782a365.693911 365.693911 0 0 0 0 731.387823z", "var(--text-ffffff)", [["class", "icon m-l-32 pointer"], ["width", 30], ["height", 30]]);
    mainContent.appendChild(img);
    mainContent.appendChild(fullHeight);
    mainContent.appendChild(searchIcon);
    header.appendChild(mainContent);
    let dialogSearch = createSearch(callback);
    document.querySelector(container).insertAdjacentElement("afterbegin", header);
    document.querySelector(container).appendChild(dialogSearch);
    searchIcon.addEventListener("click", () => {
        dialogSearch.showModal();
    });
};

function createSearch(callback){
    let dialog = createTag("dialog", [["class", "search"]]);
    let fullScreen = createTag("div", [["class", "fullScreen rowCenterCenter rela"]]);
    let dialogClose = createTag("div", [["class", "dialogClose"]]);
    let svg = createSvg("M799.86 166.31c.02 0 .04.02.08.06l57.69 57.7c.04.03.05.05.06.08a.12.12 0 010 .06c0 .03-.02.05-.06.09L569.93 512l287.7 287.7c.04.04.05.06.06.09a.12.12 0 010 .07c0 .02-.02.04-.06.08l-57.7 57.69c-.03.04-.05.05-.07.06a.12.12 0 01-.07 0c-.03 0-.05-.02-.09-.06L512 569.93l-287.7 287.7c-.04.04-.06.05-.09.06a.12.12 0 01-.07 0c-.02 0-.04-.02-.08-.06l-57.69-57.7c-.04-.03-.05-.05-.06-.07a.12.12 0 010-.07c0-.03.02-.05.06-.09L454.07 512l-287.7-287.7c-.04-.04-.05-.06-.06-.09a.12.12 0 010-.07c0-.02.02-.04.06-.08l57.7-57.69c.03-.04.05-.05.07-.06a.12.12 0 01.07 0c.03 0 .05.02.09.06L512 454.07l287.7-287.7c.04-.04.06-.05.09-.06a.12.12 0 01.07 0z", "var(--text-333333)",[["width", 32], ["height",32]]);
    let form = createTag("form", [["class", "rowStartCenter"]]);
    let divInput = createTag("div", [["class", "input"]]);
    let input = createTag("input", [["type", "text"], ["placeholder", "请输入关键字查询"], ["class", "font-16"]]);
    let button = createTag("button", [["type", "submit"]], "查询");
    divInput.appendChild(input);
    form.appendChild(divInput);
    form.appendChild(button);
    dialogClose.appendChild(svg);
    fullScreen.appendChild(dialogClose);
    fullScreen.appendChild(form);
    dialog.appendChild(fullScreen);
    form.addEventListener("submit", (event) => {
        event.preventDefault();
        try {
            const keyword = event.target.querySelector("input").value.trim();
            if(!keyword) {
                dialog.close();
                notification({
                    title: "搜索提示",
                    message: '请输入关键字查询',
                    type: 'warning'
                });
                return;
            };
            dialog.close();
            callback(keyword);
            event.target.querySelector("input").value = "";
        } catch (error) {
            console.error('搜索提交错误:', error);
            dialog.close();
            notification({
                title: "系统错误",
                message: '搜索功能暂时不可用',
                type: 'error'
            });
        }
    });
    svg.addEventListener("click", function (e){
        e.stopPropagation();
        const input = this.closest('.fullScreen').querySelector('input[type="text"]');
        input.value = '';
        dialog.close();
    });
    return dialog;
};

function createFooter(container) {
    let footer = createTag("footer", [["class", "footer columnCenterCenter font-16"]]);
    let yqlj = createTag("div", [["class", "rowStartCenter"]]);
    const urls = [
        {url: `${window.location.protocol}//${window.location.hostname}:5321`, name: "个人博客"},
        {url: `${window.location.protocol}//${window.location.hostname}:5322`, name: "管理后台"},
        {url: `${window.location.protocol}//${window.location.hostname}:5320/pages/loading/index.html`, name: "加载动画"},
        {url: "JavaScript: void 0;", name: "开放平台"}
    ];
    const info = ["电话：17798421645", ["QQ：2838719568"], ["邮箱：2838719568@qq.com"], ["网址：https://gitee.com/wang-shaoxiang/fps.git"]];
    for(let i = 0; i < urls.length; i++){
        let span = "";
        if(i !== 0) {
            span = createTag("span");
            yqlj.appendChild(span);
        };
        let a = createTag("a", [["href", urls[i].url]], urls[i].name);
        yqlj.appendChild(a);
    };
    let userInfo = createTag("div", [["class", "rowStartCenter"]]);
    info.forEach((item, index) => {
        let useInfo = createTag("div", [["class", "m-r-8 m-l-8"]], item);
        userInfo.appendChild(useInfo);
    });
    let add = createTag("div", [["class", "rowStartCenter"]], "地址：云南省昆明市");
    footer.appendChild(yqlj);
    footer.appendChild(userInfo);
    footer.appendChild(add);
    document.querySelector(container).appendChild(footer);
};